//
//  CSKey.m
//  CreateWithSuper
//
//  Created by chenjunbo on 2024/7/4.
//  Copyright © 2024 CS. All rights reserved.
//

#import "CSKey.h"
#import <Security/Security.h>
#import <CommonCrypto/CommonDigest.h>

@implementation CSKey
+ (NSString *)getKey{
    
    NSString *keychain = (NSString *)[self loadService];
    
    if (!keychain ||[keychain isEqualToString:@""]||[keychain isKindOfClass:[NSNull class]]) {
        CFUUIDRef uuid = CFUUIDCreate(nil);
        CFStringRef uuidString = CFUUIDCreateString(nil,uuid);
        NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
        CFRelease(uuid);
        CFRelease(uuidString);

        NSMutableDictionary *keychainQuery = [self infoKeychainQuery];
        SecItemDelete((CFDictionaryRef)keychainQuery);
        [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:result] forKey:(id)kSecValueData];
        SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
        keychain = (NSString *)[self loadService];
    }
    
    keychain = [keychain stringByReplacingOccurrencesOfString:@"-" withString:@""];

    return [keychain substringToIndex:11].lowercaseString;
}

+ (id)loadService{
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self infoKeychainQuery];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

+ (NSMutableDictionary *)infoKeychainQuery {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            [[NSBundle mainBundle]bundleIdentifier], (id)kSecAttrService,
            [[NSBundle mainBundle]bundleIdentifier], (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}
@end
